// 获取DOM元素
const modal = document.getElementById("myModal");
const modal1 = document.getElementById("myModal1");
const btn = document.getElementById("myBtn");
const winnerListBtn = document.getElementById("winnerListBtn");
const span = document.getElementsByClassName("close")[0];
const span1 = document.getElementsByClassName("close1")[0];
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const resultDiv = document.getElementById("result");
const flicker = document.getElementById("flicker");
const personListTextarea = document.getElementById("personList");
const personCountInput = document.getElementById("personCount");
const winnerListTextarea = document.getElementById("winnerList");

// 初始化变量
let timer = null;
let nameList = [];
let winnerList = [];

// 信息显示状态
let displayState = {
    avatar: false,     // 头像显示状态，默认显示
    lastname: false,  // 姓氏显示状态
    firstname: false, // 名字显示状态
    id: false        // 工号显示状态
};

// 遮蔽文本
function maskText(text, type) {
    if (!text) return '';
    if (type === 'lastname') {
        return displayState.lastname ? text.charAt(0) : '*';
    } else if (type === 'firstname') {
        // 处理中间名字和名字
        const remainingChars = text.slice(0);
        return displayState.firstname ? remainingChars : '*'.repeat(remainingChars.length);
    } else if (type === 'id') {
        return displayState.id ? text : '*'.repeat(text.length);
    }
    return text;
}

// 检查图片是否存在
async function checkImageExists(url) {
    return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => resolve(true);
        img.onerror = () => resolve(false);
        img.src = url;
    });
}

// 切换信息显示状态
function toggleInfo(type) {
    displayState[type] = !displayState[type];
    const button = document.getElementById('toggle' + type.charAt(0).toUpperCase() + type.slice(1));
    button.classList.toggle('active');
    
    // 如果有中奖结果，更新显示
    if (document.getElementById('result').style.display === 'block') {
        updateWinnerDisplay();
    }
}

// 切换全部显示/隐藏状态
function toggleAll() {
    const button = document.getElementById('toggleAll');
    const isShowingAll = button.classList.contains('active');
    
    // 更新按钮文本和状态
    button.textContent = isShowingAll ? '全部显示' : '全部隐藏';
    button.classList.toggle('active');
    
    // 更新所有显示状态
    for (let key in displayState) {
        displayState[key] = !isShowingAll;
        const toggleButton = document.getElementById('toggle' + key.charAt(0).toUpperCase() + key.slice(1));
        if (toggleButton) {
            if (!isShowingAll) {
                toggleButton.classList.add('active');
            } else {
                toggleButton.classList.remove('active');
            }
        }
    }
    
    // 更新显示
    if (document.getElementById('result').style.display === 'block') {
        updateWinnerDisplay();
    }
}

// 更新中奖者显示
async function updateWinnerDisplay() {
    const winners = document.querySelectorAll('.winner-card');
	
    for (const card of winners) {
        const avatar = card.querySelector('.winner-avatar');
        const nameDiv = card.querySelector('.winner-name');
        const idDiv = card.querySelector('.winner-id');
        const fullName = nameDiv.getAttribute('data-name') || '';
        const fullId = idDiv.getAttribute('data-id') || '';
        const avatarPath = avatar.getAttribute('data-src');
		console.log("update");
        
        // 更新头像显示
        if (!displayState.avatar) {
            avatar.src = 'pic/default-avatar.png';
        } else {
            // 检查实际头像是否存在
            const exists = await checkImageExists(avatarPath);
            avatar.src = exists ? avatarPath : 'pic/default-avatar2.png';
        }
        
        // 更新姓名显示（姓氏和名字分开处理）
        const lastname = maskText(fullName.charAt(0), 'lastname');
        const firstname = maskText(fullName.slice(1), 'firstname');
        nameDiv.textContent = lastname + firstname;
        
        // 更新工号显示
        idDiv.textContent = maskText(fullId, 'id');
    }
}

//显示单个头像
async function updateOneWinnerAvatarDisplay(){
	const winners = document.querySelectorAll('.winner-card');
	
    for (const card of winners) {
        const avatar = card.querySelector('.winner-avatar');
		const avatarPath = avatar.getAttribute('data-src');
        
        // 更新头像显示
        if (avatar.src.includes('default-avatar.png')) {
            const exists = await checkImageExists(avatarPath);
            avatar.src = exists ? avatarPath : 'pic/default-avatar2.png';
			break;
        }else{
			if(card == winners[winners.length -1]){
				toggleInfo('avatar');
			}
		}
    }
}

//显示单个名字
async function updateOneWinnerNameDisplay(){
	const winners = document.querySelectorAll('.winner-card');
	
    for (const card of winners) {
        const nameDiv = card.querySelector('.winner-name');
        const fullName = nameDiv.getAttribute('data-name') || '';
		console.log("fullName",fullName);
		var lastname = nameDiv.textContent.charAt(0);
		console.log("lastname",lastname);
		var firstname = nameDiv.textContent.slice(1);
		console.log("firstname",firstname);
        
        // 更新名字显示
        if (firstname.includes('*')) {
			firstname = fullName.slice(1);
			nameDiv.textContent = lastname + firstname;
			break;
        } else{
			if(card == winners[winners.length -1]){
				toggleInfo('firstname');
			}
		}
    }
}

//显示单个工号
async function updateOneWinnerIdDisplay(){
	const winners = document.querySelectorAll('.winner-card');
	
    for (const card of winners) {
        const idDiv = card.querySelector('.winner-id');
        const fullId = idDiv.getAttribute('data-id') || '';
        
        // 更新名字显示
        if (idDiv.textContent.includes('*')) {
			idDiv.textContent = fullId;
			break;
        } else{
			if(card == winners[winners.length -1]){
				toggleInfo('id');
			}
		}
    }
}

// 创建3行5列的表格HTML
function createTableHtml(people, showDetails = false) {
    const peopleCount = people.length;
    let html = '<table class="result-table' + (showDetails ? '' : ' drawing') + '">';

    if (peopleCount <= 3) {
        // 3人或更少时，创建一行，并用空列实现居中
        html += '<tr>';
        // 计算左右两边需要的空列数
        const emptyColsEachSide = Math.floor((5 - peopleCount) / 2);
        
        // 添加左边的空列
        for (let i = 0; i < emptyColsEachSide; i++) {
            html += '<td></td>';
        }
        
        // 添加中奖者
        for (let i = 0; i < peopleCount; i++) {
            html += '<td>';
            if (showDetails) {
                // 显示完整信息（头像、姓名、工号）
                const person = people[i];
                html += '<div class="winner-card">';
                const avatarPath = `pic/${person.avatar}`;
                if(displayState.avatar){
                    html += `<img src="${avatarPath}" class="winner-avatar" data-src="${avatarPath}">`;
                }else{
                    html += `<img src="pic/default-avatar.png" class="winner-avatar" data-src="${avatarPath}">`;
                }
                
                html += `<div class="winner-name" data-name="${person.name || ''}">`;
                html += maskText((person.name || '').charAt(0), 'lastname') + maskText((person.name || '').slice(1), 'firstname');
                html += '</div>';
                html += `<div class="winner-id" data-id="${person.id || ''}">${maskText(person.id || '', 'id')}</div>`;
                html += '</div>';
            } else {
                // 只显示姓名
                html += (people[i].name || '');
            }
            html += '</td>';
        }
        
        // 添加右边的空列
        const remainingCols = 5 - emptyColsEachSide - peopleCount;
        for (let i = 0; i < remainingCols; i++) {
            html += '<td></td>';
        }
        html += '</tr>';
        
        // 添加剩余的空行
        for (let i = 1; i < 3; i++) {
            html += '<tr>';
            for (let j = 0; j < 5; j++) {
                html += '<td></td>';
            }
            html += '</tr>';
        }
    } else {
        // 4人或更多时使用标准布局
        for (let i = 0; i < 3; i++) {
            html += '<tr>';
            for (let j = 0; j < 5; j++) {
                const index = i * 5 + j;
                html += '<td>';
                if (index < people.length) {
                    if (showDetails) {
                        // 显示完整信息（头像、姓名、工号）
                        const person = people[index];
                        html += '<div class="winner-card">';
                        const avatarPath = `pic/${person.avatar}`;
                        if(displayState.avatar){
                            html += `<img src="${avatarPath}" class="winner-avatar" data-src="${avatarPath}">`;
                        }else{
                            html += `<img src="pic/default-avatar.png" class="winner-avatar" data-src="${avatarPath}">`;
                        }
                        
                        html += `<div class="winner-name" data-name="${person.name || ''}">`;
                        html += maskText((person.name || '').charAt(0), 'lastname') + maskText((person.name || '').slice(1), 'firstname');
                        html += '</div>';
                        html += `<div class="winner-id" data-id="${person.id || ''}">${maskText(person.id || '', 'id')}</div>`;
                        html += '</div>';
                    } else {
                        // 只显示姓名
                        html += (people[index].name || '');
                    }
                }
                html += '</td>';
            }
            html += '</tr>';
        }
    }
    html += '</table>';
    return html;
}

// 解析人员信息
function parsePersonInfo(line) {
    const parts = line.split(',').map(part => part.trim());
    if (parts.length >= 4) {
        return {
            name: parts[0],
            id: parts[1],
            department: parts[2],
            avatar: parts[3]
        };
    }
    return null;
}

// 打开录入名单模态框
function openModal() {
    modal.style.display = "block";
}

// 打开中奖记录模态框
function openWinnerList() {
    modal1.style.display = "block";
    displayWinnerList();
}

// 从localStorage加载数据
function loadData() {
    const savedNameList = localStorage.getItem('nameList');
    if (savedNameList) {
        nameList = JSON.parse(savedNameList);
        personListTextarea.value = nameList.map(person => 
            `${person.name},${person.id},${person.department},${person.avatar}`
        ).join('\n');
    }
    // 清空中奖记录
    winnerList = [];
    localStorage.removeItem('winnerList');
    displayWinnerList();
}

// 页面加载时初始化数据
window.onload = function() {
    loadData();
    // 初始化按钮状态
    stopBtn.style.display = 'none';
    resultDiv.style.display = 'none';
    
    // 绑定事件监听器
    span.onclick = function() {
        modal.style.display = "none";
    }

    span1.onclick = function() {
        modal1.style.display = "none";
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
        if (event.target == modal1) {
            modal1.style.display = "none";
        }
    }
}

// 关闭录入名单模态框
function closeModal() {
    modal.style.display = "none";
}

// 关闭中奖记录模态框
function closeModal1() {
    modal1.style.display = "none";
}

// 保存人员名单
function savePersonList() {
    const text = personListTextarea.value;
    nameList = text.split('\n')
        .map(line => parsePersonInfo(line))
        .filter(person => person !== null);
    localStorage.setItem('nameList', JSON.stringify(nameList));
    closeModal();
}

// 增加抽奖人数
function increasePersonCount() {
    let currentValue = parseInt(personCountInput.value);
    if (currentValue < 15) {
        personCountInput.value = currentValue + 1;
    } else {
        alert('最多只能抽取15人');
    }
}

// 处理人数输入
personCountInput.addEventListener('input', function() {
    let value = parseInt(this.value);
    if (value > 15) {
        alert('最多只能抽取15人');
        this.value = 15;
    } else if (value < 1) {
        this.value = 1;
    }
});

// 防止输入非数字
personCountInput.addEventListener('keypress', function(e) {
    if (!/[\d]/.test(e.key)) {
        e.preventDefault();
    }
});

// 失去焦点时确保值的有效性
personCountInput.addEventListener('blur', function() {
    let value = this.value.trim();
    if (value === '' || isNaN(value)) {
        this.value = 1;
    }
});

// 减少抽奖人数
function decreasePersonCount() {
    const currentValue = parseInt(personCountInput.value);
    if (currentValue > 1) {
        personCountInput.value = currentValue - 1;
    }
}

// 开始抽奖
function playFun() {
    if (nameList.length === 0) {
        alert('请先录入人员名单！');
        return;
    }

    const count = parseInt(personCountInput.value);
    if (count > nameList.length) {
        alert(`当前名单只有${nameList.length}人，不能抽取${count}人！`);
        return;
    }

    startBtn.style.display = 'none';
    stopBtn.style.display = 'inline-block';
	resultDiv.style.display =  'block';
    flicker.style.display = 'block';
	resultDiv.innerHTML = '';

    if (timer) {
        clearInterval(timer);
    }

    timer = setInterval(() => {
        let result = [];
        // 随机抽取20个名字用于动画效果
        const displayCount = Math.min(20, nameList.length);
        const tempList = [...nameList];
        for (let i = 0; i < displayCount; i++) {
            if (tempList.length === 0) break;
            const randomIndex = Math.floor(Math.random() * tempList.length);
            result.push(tempList[randomIndex]);
            tempList.splice(randomIndex, 1);
        }
        flicker.innerHTML = createTableHtml(result, false); // 动画过程中只显示姓名
    }, 50);
}

// 停止抽奖
function stopFun() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
    startBtn.style.display = 'inline-block';
    stopBtn.style.display = 'none';

    // 抽取最终的中奖名单
    const count = parseInt(personCountInput.value);
    const tempList = [...nameList];
    const winners = [];
    
    for (let i = 0; i < count; i++) {
        if (tempList.length === 0) break;
        const randomIndex = Math.floor(Math.random() * tempList.length);
        winners.push(tempList[randomIndex]);
        tempList.splice(randomIndex, 1);
    }

    // 显示最终中奖名单（包含头像和工号）
	flicker.innerHTML = '';
    resultDiv.innerHTML = createTableHtml(winners, true);

    // 记录中奖记录
    const timestamp = new Date().toLocaleString();
    winnerList.push({ 
        timestamp, 
        winners: winners.map(w => ({name: w.name, id: w.id}))
    });
    localStorage.setItem('winnerList', JSON.stringify(winnerList));
    displayWinnerList();

    // 从名单中移除已中奖的人
    winners.forEach(winner => {
        const index = nameList.findIndex(p => p.id === winner.id);
        if (index > -1) {
            nameList.splice(index, 1);
        }
    });
    localStorage.setItem('nameList', JSON.stringify(nameList));
    personListTextarea.value = nameList.map(person => 
        `${person.name},${person.id},${person.department},${person.avatar}`
    ).join('\n');
}

// 显示中奖记录
function displayWinnerList() {
    let displayText = '';
    winnerList.forEach((record, index) => {
        displayText += `第${index + 1}次抽奖 (${record.timestamp})\n`;
        displayText += `中奖名单：\n`;
        record.winners.forEach(winner => {
            displayText += `${winner.name} (工号: ${winner.id})\n`;
        });
        displayText += '----------------------------------------\n';
    });
    winnerListTextarea.value = displayText;
}

// 更换logo图片
async function changeLogo(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
        alert('请选择图片文件');
        return;
    }
    
    // 检查文件大小（限制为2MB）
    if (file.size > 2 * 1024 * 1024) {
        alert('图片大小不能超过2MB');
        return;
    }
    
    try {
        // 读取文件并转换为Base64
        const reader = new FileReader();
        reader.onload = function(e) {
            // 更新logo图片
            const logoImg = document.querySelector('.logo');
            if (logoImg) {
                // 保存到localStorage
                localStorage.setItem('customLogo', e.target.result);
                // 更新显示
                logoImg.src = e.target.result;
            }
        };
        reader.readAsDataURL(file);
    } catch (error) {
        console.error('更换logo失败:', error);
        alert('更换logo失败，请重试');
    }
    
    // 清空input，确保可以重复选择同一个文件
    event.target.value = '';
}

// 页面加载时检查是否有自定义logo
window.addEventListener('load', function() {
    const customLogo = localStorage.getItem('customLogo');
    if (customLogo) {
        const logoImg = document.querySelector('.logo');
        if (logoImg) {
            logoImg.src = customLogo;
        }
    }
});
